package com.talking.view;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.hmsscankit.WriterException;
import com.huawei.hms.ml.scan.HmsBuildBitmapOption;
import com.huawei.hms.ml.scan.HmsScan;
import com.talking.App;
import com.talking.R;
import com.talking.databinding.ActivityPersonBinding;
import com.talking.databinding.DialogAddFriendBinding;
import com.talking.model.Http;
import com.talking.presenter.FriendPresenter;
import com.talking.presenter.MessagePresenter;
import com.talking.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Objects;

import jp.wasabeef.glide.transformations.BlurTransformation;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PersonActivity extends AppCompatActivity {
    private ActivityPersonBinding binding;
    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding= ActivityPersonBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        Glide.with(this).load(Http.BASE_URL+ App.userBean.iconUrl).apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 8))).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.personIconBg);
        Glide.with(this).load(Http.BASE_URL+ App.userBean.iconUrl).apply(Utils.getGlideOption()).placeholder(R.drawable.loading).placeholder(R.drawable.loading).error(R.drawable.loaderr).into(binding.personIcon);
        FriendPresenter.querySingle(App.sp.getString("account",""),App.userBean.account, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }
            @SuppressLint("SetTextI18n")
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                runOnUiThread(() -> {
                    try {
                       String result = response.body().string();
                        if (result.equals("没得好友")){
                            binding.personAccount.setText(App.userBean.account);
                            binding.personNickname.setText(App.userBean.nickname);
                            binding.personDelete.setVisibility(View.GONE);
                            binding.personSendMsg.setEnabled(false);
                            binding.personOp.setText("添加好友");
                        }else{
                            JSONObject jo = new JSONObject(result);
                            binding.personAccount.setText(App.userBean.account);
                            binding.personNickname.setText(jo.getString("remark")+"("+App.userBean.nickname+")");
                            binding.personSendMsg.setEnabled(true);
                            binding.personOp.setText("修改备注");
                            binding.personDelete.setVisibility(View.VISIBLE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (android.R.id.home==item.getItemId()){ finish(); }
        return super.onOptionsItemSelected(item);
    }
    public void operation(View view){
        if (binding.personOp.getText().toString().equals("修改备注")){
            AlertDialog.Builder dialog=new AlertDialog.Builder(this);
            EditText edit=new EditText(this);
            edit.setHint("请输入备注名");
            dialog.setTitle("修改备注").setView(edit).setPositiveButton("修改", (dialog1, which) -> {
                if (edit.getText().toString().equals("")){
                    Utils.toast( "请输入备注名");
                }else{
                    App.chatingRemark=edit.getText().toString();
                    FriendPresenter.modifyRemark(App.sp.getString("account", ""), App.userBean.account, edit.getText().toString(), new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {e.printStackTrace();}
                        @SuppressLint("SetTextI18n")
                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) {
                            runOnUiThread(() -> {
                                try {
                                    String res = response.body().string();
                                    if (res.equals("修改成功")){
                                        binding.personNickname.setText(edit.getText().toString()+"("+App.userBean.nickname+")");
                                    }else {
                                        Utils.toast( res);
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            });
                        }
                    });
                }
            }).setNegativeButton("取消",null).setCancelable(false).show();
        }else if (binding.personOp.getText().toString().equals("添加好友")){
            if (App.userBean.account.equals(App.sp.getString("account",""))){
                Utils.toast( "您不能添加自己为好友");
            }else {
                AlertDialog.Builder dialog=new AlertDialog.Builder(this);
                @NonNull DialogAddFriendBinding dialog_binding = DialogAddFriendBinding.inflate(getLayoutInflater());
                dialog.setTitle("添加好友").setView(dialog_binding.getRoot()).setPositiveButton("添加", (dialog1, which) -> {
                    try {
                        MessagePresenter.addMessage("加好友", App.sp.getString("account", ""), App.userBean.account, new JSONObject().put("greet",dialog_binding.dialogGreet.getText().toString()).put("remarks",dialog_binding.dialogRemarks.getText().toString()), new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                runOnUiThread(() -> Utils.toast( e.toString()));
                            }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                runOnUiThread(()->{
                                    try {
                                        if (response.body().string().equals("添加消息完成")){
                                            Utils.toast( "已发送好友请求");
                                        }else {
                                            Utils.toast( response.body().string());
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }).setNegativeButton("取消",null).setCancelable(false).show();
            }
        }
    }
    public void sendMsg(View view){
        App.chatingWith=App.userBean.account;
        startActivity(new Intent(PersonActivity.this,ChatActivity.class));
    }
    public void delete(View view){
        AlertDialog.Builder dialog=new AlertDialog.Builder(this);
        dialog.setTitle("确认删除").setMessage("删除后聊天记录等信息也会删除").setPositiveButton("删除", (dialog12, which) -> FriendPresenter.delete(App.sp.getString("account",""), App.userBean.account, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                runOnUiThread(() -> {
                    try {
                        String result = response.body().string();
                        if (result.equals("删除好友成功")){
                            finish();
                        }
                        Utils.toast( result);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
        })).setNegativeButton("",null).show();
    }
    public void qrCode(View view){
        ImageView iv=new ImageView(this);
        try {
            iv.setImageBitmap(ScanUtil.buildBitmap("add:"+ App.userBean.account, HmsScan.QRCODE_SCAN_TYPE, 400, 400, new HmsBuildBitmapOption.Creator().setBitmapBackgroundColor(Color.WHITE).setBitmapColor(Color.rgb(240,99,101)).setBitmapMargin(3).create()));
            AlertDialog.Builder dialog=new AlertDialog.Builder(this);
            dialog.setTitle("扫一扫添加").setView(iv).setPositiveButton("确定", null).show();
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
    public void openMoment(View view){
        App.momentAccount=App.userBean.account;
        startActivity(new Intent(PersonActivity.this,MomentActivity.class));
    }
}
